package com.gaohe.interceptor;

import com.gaohe.common.BaseContext;
import com.gaohe.common.PathMatcher;
import com.gaohe.common.RedisCache;
import com.gaohe.common.ResultCode;
import com.gaohe.pojo.Admin;
import com.gaohe.pojo.User;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.List;
import java.util.Objects;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedisCache redisCache;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.登录  js css
        //1.1获取请求路径
        String uri = request.getRequestURI();
        boolean check = PathMatcher.check(uri);
        if (check) {
            log.info("放行：" + uri);
            return true;
        }
        //2.已经登陆
//        Object loginAdmin = request.getSession().getAttribute("loginAdmin");
        String redisKey = "admin_" + request.getHeader("admin");
        Admin redisAdmin = (Admin) redisTemplate.opsForValue().get(redisKey);
        if (Objects.nonNull(redisAdmin)) {
            //用户名存入线程空间
            BaseContext.setUsername(redisAdmin.getUsername());
            return true;
        }
        //会员
        String memberKey = "user_" + request.getHeader("auth");
        User user = redisCache.getCacheObject(memberKey);
        if (Objects.nonNull(user)) {
            //用户名存入线程空间
            BaseContext.setUsername(user.getUsername());
            return true;
        }

        //3.拦截 返回标识
        response.setStatus(ResultCode.NOT_LOGIN);
        return false;
    }
}
